package com.docmanage.common.utils;

import cn.hutool.core.collection.CollUtil;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @author yhd
 * @create 2024/3/7 17:41
 */
public class TreeUtils {

    public static final String DEFAULT_PARENT_ID = "0";

    /**
     * 构建节点树
     * @param treeNodeList 节点列表
     * @param <T> 节点类型
     * @return 节点树
     */
    public static <T extends TreeNode> List<T> build(List<T> treeNodeList, String parentId) {
        if (CollUtil.isEmpty(treeNodeList)) {
            return Collections.emptyList();
        }

        List<T> treeList = new ArrayList<>();

        for (T treeNode : treeNodeList) {
            if (Objects.equals(treeNode.getParentId(), parentId)) {
                treeList.add(treeNode);
            }

            for (T node : treeNodeList) {
                if (Objects.equals(node.getParentId(), treeNode.getId())) {
                    if (Objects.isNull(treeNode.getChildren())) {
                        treeNode.setChildren(CollUtil.list(false));
                    }
                    treeNode.add(node);
                }
            }
        }

        return treeList;
    }
}
